package com.liull.netty.nio.handler;

import java.util.Scanner;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author: liull
 * @Description:
 * @Date: Created in 12:39 2021/7/24
 * @Modified By:
 */
@Slf4j
public class TestHandlerClient {
    public static void main(String[] args) throws InterruptedException {
        final NioEventLoopGroup group = new NioEventLoopGroup();
        final ChannelFuture future = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                        ch.pipeline().addLast(new StringEncoder());
                    }
                })
                .connect("localhost", 8989);
        future.sync();
        final Channel channel = future.channel();
        new Thread(() -> {
            Scanner sc = new Scanner(System.in);
            while (true) {
                String input = sc.nextLine();
                if ("q".equals(input)) {
                    // todo 为什么
                    channel.close();
                    break;
                } else {
                    channel.writeAndFlush(input);
                }
            }
        }, "Thread-input").start();

        // 异步close
        final ChannelFuture closeFuture = channel.closeFuture();
        log.debug("等待连接close");
        closeFuture.sync();
        log.debug("处理关闭之后的操作");
        // 加上这一句就可以关掉客户端进程啦
        group.shutdownGracefully();
    }
}
